#pragma once
#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace LogMudule;

const static uint16_t defaultport = 8888;
// const static std::string defaultip = "62.234.18.77";

class UDPSever
{
public:
    UDPSever(uint16_t port = defaultport) : _in_addr(port), _isrunning(false)
    {
        // 1. 创建套接字
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error";
            exit(1);
        }
        LOG(LogLevel::DEBUG) << "socket succeed";

        // 2. 绑定
        int n = ::bind(_sockfd, _in_addr.NetAddr(), _in_addr.Len());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            exit(2);
        }
        LOG(LogLevel::DEBUG) << "bind succeed";
    }
    void Run()
    {
        _isrunning = true;
        char buff[1024];

        // 定义接收发送消息的主机的addr信息的结构
        struct sockaddr_in src_addr;
        socklen_t len;

        while (true)
        {
            // 接收来自客户端的信息
            int n = ::recvfrom(_sockfd, buff, sizeof(buff) - 1, 0, (struct sockaddr *)&src_addr, &len);
            InetAddr cli(src_addr);
            if (n > 0)
            {
                buff[n] = '\0';
                LOG(LogLevel::INFO) << cli.Ip() << ":" << cli.Port() << "Clint say#" << buff;

                std::string message = "Echo#";
                message += buff;
                // 将包装的信息发送给源主机
                ::sendto(_sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&src_addr, len);
            }
        }
        _isrunning = false;
    }
    ~UDPSever()
    {
        close(_sockfd);
    }

private:
    int _sockfd;
    InetAddr _in_addr; // 用InetAddr 来管理转化操作
    bool _isrunning;
};